import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;



public class BuildHuffman {
	
	static HuffNode[] data=new HuffNode['z'-'a'+2];
	static char c;
	static int items=0;
	
	private static void processString(String inputString){
		inputString=inputString.toLowerCase();
		inputString=inputString.replace(" ", "");
		String[] line=inputString.split(":");
		char letter=line[0].charAt(0);
		int size=Integer.parseInt(line[1]);
		HuffNode node=new HuffNode(letter, size);
		data[items+1]=node;
		System.out.println(data[items]);
		items++;
	}
	
	public static void main(String[] args)
	{
		System.out.println(System.getProperties().getProperty("user.dir"));
		
		String inputFile = args[0];
		//String inputFile = ".\\src\\Example1\\out1-1.txt";
		//String inputFile = ".\\src\\Example2\\out2-1.txt";
		String outputFile = args[1];
		//String outputFile=inputFile+"_processed.txt";
		
		read_From_File(inputFile);
		
		HuffMinHeap sorted=new HuffMinHeap(data,items);

		System.out.println("Starting.... drinking, sorting & printing\n");
		
		/*
	HuffNode tmp=sorted.getNextMin();
		while (tmp!=null){
			System.out.println(tmp);
			tmp=sorted.getNextMin();
		}
		System.out.println("Done drinking, sorting & printing\n");
*/
		//build HuffTree
		HuffNode z=null;
		HuffNode left;
		HuffNode right;
		for (int i=1;i<items;i++){
			right=sorted.extractMin();
			left=sorted.extractMin();
			System.out.println("handled "+right.c+" & "+left.c);
			if (i==items-1)
				//to make output same as example... argggg
				z=new HuffNode(left.size+right.size, right, left);
			else
				z=new HuffNode(left.size+right.size, left, right);
			sorted.insert(z);
		}
		HuffNode huffTree=z;
		
		//getting nodes strings
		String paths=huffTree.getNodesStrings();
		System.out.println("paths returned are: "+paths);
		String[] pathsArray=paths.split(";");
		
		//building a new array according to Output file format
		String[] item;
		int treeCost=0;
		String[] letters=new String[27];
		System.out.println("Starting to break paths...");
		for (int i=0;i<pathsArray.length;i++){
			if (pathsArray[i]!=null && pathsArray[i].length()>0){
				System.out.print(pathsArray[i] +"  ");
				item=pathsArray[i].split(",");
				System.out.println("\t\t"+item[0]+":"+item[1]);
				letters[item[0].codePointAt(0)-'a']=item[0]+":"+item[1];
				treeCost=treeCost+Integer.parseInt(item[2]);
			}
		}
		System.out.println("Sum="+treeCost);
		
		//writing to file
		write_To_File(outputFile,letters,treeCost);
		
	}
	
	private static void write_To_File(String outputFilename,String[] lines,int sum) {

        System.out.println("Writing to file " + outputFilename);
        
        
        try {
            File outFile = new File(outputFilename);
            FileWriter ofw = new FileWriter(outFile);
            String line;
            //Writing to file
            for (int i=0;i<lines.length;i++)
            	if (lines[i]!=null && lines.length>0){
            		line=lines[i]+System.getProperty("line.separator");
            		System.out.println(line);
            		ofw.write(line);
            	}
            line="sum="+sum+System.getProperty("line.separator");
            System.out.println(line);
            ofw.write(line);
          	
            ofw.close();
            
            System.out.println("Wrote to file " + outputFilename);
            
        }
        catch (Exception e) {
            System.out.println( "Error \""+ e.toString()+ "\" on file "+outputFilename);
            e.printStackTrace() ;
            System.exit(-1) ;      //brutally exit the program
        }

    }
	public static void read_From_File(String inputFilename){
       	System.out.println("Reading from file " + inputFilename);
       
       	try {
            File inFile = new File(inputFilename);
            FileReader ifr = new FileReader(inFile);
            BufferedReader ibr= new BufferedReader(ifr) ;

            String line = "" ;
            while (line != null )
            {
                line = ibr.readLine() ;
                if (line != null)
                {
                    StringTokenizer st = new StringTokenizer(line); // splits the line into tokens
					
                    while(st.hasMoreTokens())
                    {
                    	String token = st.nextToken().trim();
                    	System.out.println(token);
                    	processString(token);
                    }                   
                }
            }

            ibr.close();
            ifr.close();
        }

        catch(Exception e) {
            System.out.println( "Error \""+ e.toString()+ "\" on file "+inputFilename);
            e.printStackTrace() ;
            System.exit(-1) ;      //brutally exit the program
        }
	
	}

}
